<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import * as userApi from '@/api/user'
import { message } from 'ant-design-vue'
import pdrLogo from '@/assets/pdr-logo.png'
import lpLogo from '@/assets/lp-logo.png'
import { useBrandStore } from '@/store/modules/brand'
const brandStore = useBrandStore()

const router = useRouter()
const route = useRoute()

const userStore = useUserStore()

const myState = reactive({
  smsSendFlag: false,
  time: 60,
})

const levelNames = ref({
  0: '低',
  1: '低',
  2: '中',
  3: '强',
})
const levelClass = ref({
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success',
})
const levelColor = ref({
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#1890ff',
})

const passwordLevel = ref(0)
const passwordLevelChecked = ref(false)
const percent = ref(10)

// 获取验证码
const getSms = async () => {
  loginForm.value?.validateFields(['userName']).then(async () => {
    let params = {
      phone: formState.value.userName,
    }
    if (params['phone'] == '') {
      message.error(`用户名不能为空~`)
      return
    }

    const hide = message.loading('验证码发送中..', 0)
    try {
      let { state, message: msg } = await userApi.sendRegSms(params)
      if (state === 200) {
        myState.smsSendFlag = true
        const interval = setInterval(() => {
          if (myState.time-- <= 0) {
            myState.time = 60
            myState.smsSendFlag = false
            clearInterval(interval)
          }
        }, 1000)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    setTimeout(hide, 1)
  })
}

let labelCol = { span: 4 }
let loginForm = ref<HTMLElement | null>(null)
interface FormState {
  invitationCode: string | number
  userName: string | number
  password: string
  confirmPassword: string
  code: string | number
}
const formState = ref<FormState>({
  invitationCode: '',
  userName: '',
  password: '',
  confirmPassword: '',
  code: '',
})

// 注册
const handleSubmit = async () => {
  // invitationCode: formState.value.invitationCode,
  const params: FormState = {
    userName: formState.value.userName,
    code: formState.value.code,
    password: formState.value.password,
    confirmPassword: formState.value.confirmPassword,
  }
  let key: keyof FormState
  for (key in params) {
    if (params[key] == '') {
      switch (key) {
        case 'userName':
          message.error(`用户名不能为空~`)
          return
        case 'code':
          message.error(`验证码不能为空~`)
          return
        case 'password':
          message.error(`密码不能为空~`)
          return
        case 'confirmPassword':
          message.error(`确认密码不能为空~`)
          return
      }
    }
  }
  try {
    const { state, message: msg } = await userApi.register(params)
    if (state === 200) {
      message.success('注册成功~')
      goLogin()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 返回登陆
const goLogin = () => {
  router.push({ path: '/login' })
}

let registerLoading = ref<boolean>(false)
const onFinish = async (values: any) => {
  const params: FormState = {
    userName: formState.value.userName,
    code: formState.value.code,
    password: formState.value.password,
    confirmPassword: formState.value.confirmPassword,
  }

  params.shareNumber = formState.value.invitationCode
  if (!checked.value) {
    message.error('请查看用户协议')
    return
  }
  //判断当前的 品牌  是否是 票务之家
  if (brandStore.documentTitle == '票务之家') {
    params.shareNumber = 'wQhjJuI4YZa'
  }
  try {
    registerLoading.value = true
    const { state, message: msg } = await userApi.register(params)
    if (state === 200) {
      message.success('注册成功~')
      let params = {
        userName: formState.value.userName,
        password: formState.value.password,
      }
      await userStore.login(params)
      router.push({ path: '/' })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  registerLoading.value = false
}

//验证手机号 是否正常
const isPhoneNumber = (rule: any, value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 假设这是中国的手机号格式
  const numberGex = /^[0-9]+$/
  if (isNaN(value)) {
    callback(new Error('请输入有效的用户名！'))
  }
  if (!phoneRegex.test(value) && value && numberGex.test(value)) {
    callback(new Error('请输入有效的用户名！'))
  } else {
    callback()
  }
}

const passwordisEqual = (rule: any, value: any, callback: any) => {
  if (formState.value.password !== value && formState.value.password && value) {
    callback(new Error('两次输入的密码不一致！'))
  } else {
    callback()
  }
}

//密码强度校验
const validatePasswordStrength = (rule: any, value: any, callback: any) => {
  const regex = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}/
  if (!regex.test(value)) {
    callback(new Error('密码至少8位，包含大小写字母、数字和特殊符号'))
  }
  callback()
}

const passwordLevelClass = computed(() => {
  return levelClass.value[passwordLevel.value]
})

const passwordLevelName = computed(() => {
  return levelNames.value[passwordLevel.value]
})

const passwordLevelColor = computed(() => {
  return levelColor.value[passwordLevel.value]
})

const handlePasswordLevel = (rule: any, value: any, callback: any) => {
  let level = 0
  if (!value) {
    callback()
    // return
  }

  // 判断这个字符串中有没有数字
  if (/[0-9]/.test(value)) {
    level++
  }

  // 判断字符串中有没有字母
  if (/[a-zA-Z]/.test(value)) {
    level++
  }

  // 判断字符串中有没有特殊符号
  if (/[^0-9a-zA-Z_]/.test(value)) {
    level++
  }

  passwordLevel.value = level
  percent.value = level * 30

  if (level >= 2) {
    if (level >= 3) {
      percent.value = 100
    }
    callback()
  } else {
    if (level === 0) {
      percent.value = 10
    }
    callback(new Error('密码强度不够!'))
  }
}

const handlePasswordLength = (rule: any, value: any, callback: any) => {
  if (value.length < 8 && value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else if (!value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else {
    callback()
  }
}

onMounted(() => {
  formState.value.invitationCode = route.query.code as string
})

let activeTab = ref<number>(2)
const changeTab = (e: number) => {
  activeTab.value = e
  if (activeTab.value == 1) router.push({ path: '/login' })
}

const userVisilble = ref(false)
const checked = ref(false)
const checkedDisabled = ref(true)
const debounceTimer = ref(null)
const successBtn = ref(true)
const handleChangeChecked = e => {
  console.log(e.target.checked, 'e.target.checked')
  checked.value = e.target.checked
}
const handleUserAgreement = () => {
  userVisilble.value = true

  setTimeout(() => {
    const box = document.querySelector('#box')
    console.log(box, 'box')
    box.addEventListener('scroll', handleScrollDebounced)
  }, 1000)
}
const handleScrollDebounced = e => {
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
  }
  debounceTimer.value = setTimeout(() => {
    handleScroll(e)
  }, 100) // 100ms的防抖延迟
}
const handleScroll = e => {
  console.log(e, 'e')
  console.log(e.target, 'e,target')
  const box = e.target
  const isAtBottom = box.scrollHeight - box.scrollTop <= box.clientHeight + 1

  if (isAtBottom) {
    onReachBottom()
  }
}
const onReachBottom = () => {
  console.log('已滚动到底部')
  successBtn.value = false
  // 在这里添加滚动到底部时要执行的逻辑
}
const readSuccess = () => {
  userVisilble.value = false
  checkedDisabled.value = false
  checked.value = true
  successBtn.value = false
}
const handleClickChecked = () => {
  if (checkedDisabled.value) {
    message.error('请查看用户协议')
    return
  }
}
</script>

<template>
  <div class="main-app">
    <div class="main-logo">
      <div class="lp-logo" v-if="brandStore.title_1">
        <img :src="brandStore.logo_1" />
        <span style="color: #6d36bb; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_1 }}
        </span>
      </div>
      <div class="vertical-line" v-if="brandStore.title_2"></div>
      <div class="pdr-logo" v-if="brandStore.title_2">
        <img :src="brandStore.logo_2" />
        <span style="color: black; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_2 }}
        </span>
      </div>
    </div>

    <div class="title-desc">
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_1 }}</i>
      </div>
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_2 }}</i>
      </div>
      <div style="font-weight: 400; font-size: 18px; letter-spacing: 10px">用技术为运营提效</div>
    </div>

    <div class="main-div">
      <a-form
        ref="loginForm"
        :model="formState"
        :label-col="labelCol"
        autocomplete="off"
        style="width: 18rem; height: 300px"
        @finish="onFinish"
      >
        <div class="tabs">
          <div class="left-box" @click="changeTab(1)">
            <div :class="{ 'password-login': activeTab === 1 }">密码登录</div>
          </div>
          <div class="right-box" @click="changeTab(2)">
            <span :class="{ 'register-account': activeTab === 2 }">注册账号</span>
          </div>
        </div>
        <!-- //判断当前的 品牌  是否是 票务之家 -->
        <a-form-item
          name="invitationCode"
          v-if="brandStore.documentTitle != '票务之家'"
          :rules="[{ required: true, message: '请输入邀请码!' }]"
        >
          <a-input v-model:value="formState.invitationCode" placeholder="邀请码" autocomplete="off">
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>
        <a-form-item
          name="userName"
          :rules="[
            { required: true, message: '请输入11位手机号!' },
            { validator: isPhoneNumber, trigger: 'blur' },
          ]"
        >
          <a-input
            v-model:value="formState.userName"
            placeholder="请输入11位手机号"
            autocomplete="off"
          >
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <a-form-item name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
          <a-input
            v-model:value="formState.code"
            placeholder="验证码"
            autocomplete="off"
            style="width: 10rem"
          >
            <template #prefix><MailOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
          <a-button
            :disabled="myState.smsSendFlag"
            v-text="(!myState.smsSendFlag && '获取验证码') || `${myState.time} s`"
            @click="getSms"
            style="margin-left: 15px; border-radius: 6px"
            type="primary"
          ></a-button>
        </a-form-item>

        <a-form-item
          name="password"
          :rules="[{ validator: handlePasswordLevel }, { validator: handlePasswordLength }]"
        >
          <a-input-password
            v-model:value="formState.password"
            type="password"
            placeholder="密码至少8位,区分大小写!"
            autocomplete="off"
            @focus="passwordLevelChecked = true"
            @blur="passwordLevelChecked = false"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>

        <div
          style="position: absolute; right: 0px; bottom: 160px; z-index: 10"
          v-if="passwordLevelChecked"
        >
          <a-popover
            v-model:open="passwordLevelChecked"
            placement="right"
            v-if="passwordLevelChecked"
          >
            <template #content>
              <div style="display: flex; justify-content: space-between">
                <div style="display: flex; align-items: center">
                  <div :class="['user-register', passwordLevelClass]" style="margin-right: 10px">
                    <span>{{ passwordLevelName }}</span>
                  </div>
                  <a-progress
                    :percent="percent"
                    :steps="3"
                    :showInfo="false"
                    :strokeColor="passwordLevelColor"
                  />
                </div>
              </div>
            </template>
          </a-popover>
        </div>

        <a-form-item
          name="confirmPassword"
          :rules="[
            { required: true, message: '请输入确认密码!' },
            { validator: passwordisEqual, trigger: 'blur' },
          ]"
        >
          <a-input-password
            v-model:value="formState.confirmPassword"
            type="password"
            placeholder="请输入确认密码"
            autocomplete="off"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>
        <div title="请仔细阅读用户协议" @click="handleClickChecked" style="margin: 10px 0">
          <a-checkbox @change="handleChangeChecked" :disabled="checkedDisabled" v-model="checked">
            我已阅读并同意
            <a @click.stop="handleUserAgreement">《用户协议》</a>
          </a-checkbox>
        </div>
        <a-form-item>
          <div style="display: flex; justify-content: space-between">
            <div>
              <a-button type="primary" html-type="submit" :loading="registerLoading">
                注册并登录
              </a-button>
            </div>
            <div style="line-height: 32px">
              <a @click="goLogin">使用已有帐号登录</a>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </div>

  <a-modal
    title="用户协议"
    :width="700"
    :visible="userVisilble"
    @cancel="userVisilble = false"
    :footer="null"
    :maskClosable="true"
  >
    <div id="box" style="height: 600px; overflow-y: auto">
      <h2 class="fonWeight" style="text-align: center">票达人CRM系统平台用户注册协议</h2>
      <p>
        本协议由您（“用户”）与票达人CRM系统平台运营方（“平台方”）订立，您注册或使用票达人CRM系统平台（以下简称
        “本平台”）即视为完全接受本协议所有条款，包括平台方未来对条款的修改。
      </p>
      <h3 class="fonWeight">一、注册资格</h3>
      <p>
        您须为具有完全民事行为能力的自然人或合法存续的组织；若为未成年人，须在监护人同意及监督下使用本平台。
      </p>
      <p>
        您承诺提供的注册信息（如姓名、联系方式、身份信息等）真实、准确、完整，且不侵犯第三方权益。
      </p>
      <h3 class="fonWeight">二、账户注册与管理</h3>
      <p>
        您需通过本平台指定流程完成注册，设置安全的账户密码。平台方有权对注册信息进行审核，若发现虚假信息，可拒绝注册或注销账户。
      </p>
      <p>
        您须妥善保管账户及密码，禁止出租、转让、出借账户。因您保管不善导致的账户风险或损失，由您自行承担。若发现账户异常，须立即联系平台方冻结账户。
      </p>
      <h3 class="fonWeight">三、用户权利与义务</h3>
      <p>1、您有权依法使用本平台提供的各项服务。</p>
      <p>2、您承诺遵守法律法规及平台规则，不得实施以下行为：</p>
      <p>A、利用本平台从事低价倾销和恶意抢购等扰乱市场秩序的活动；</p>
      <p>B、破坏平台系统安全、数据完整性或干扰平台正常运行；</p>
      <p>C、传播违法信息（如暴力、色情、欺诈内容等）或侵犯他人知识产权、隐私权等权益；</p>
      <p>D、其他违反诚实信用原则或损害平台方、其他用户利益的行为。</p>
      <p>
        若您违反上述义务，平台方有权采取警告、限制功能、注销账户等措施，您须承担全部法律责任及对平台方造成的损失赔偿。
      </p>
      <h3 class="fonWeight">四、平台服务说明</h3>
      <p>
        平台方致力于提供稳定、安全的服务，但不保证服务无中断、无错误。因不可抗力（如自然灾害、网络攻击）、第三方原因（如通信运营商故障）或您自身设备、网络问题导致的服务异常，平台方不承担责任。
      </p>
      <p>
        平台方有权根据业务调整、技术升级等需要，暂停、变更或终止部分服务或功能，但会通过公告等方式通知。
      </p>
      <h3 class="fonWeight">五、退费条款</h3>
      <p>用户有权申请退费，需满足下列条件之一：</p>
      <p>1、基于平台系统功能的自动化业务发生故障并在14天内未恢复，致使用户业务无法进行；</p>
      <p>2、平台关闭并停止运营的情形；</p>
      <h3 class="fonWeight">六、隐私保护</h3>
      <p>
        平台方严格遵守《中华人民共和国个人信息保护法》，收集的用户信息（如注册信息、支付信息等）仅用于提供服务、优化体验、保障安全等目的，未经您同意不向第三方披露（法律另有规定或为保护平台方及用户合法权益除外）。
      </p>
      <h3 class="fonWeight">七、协议变更</h3>
      <p>
        平台方有权随时修改本协议条款，修改后的协议将通过站内信、弹窗、公告等方式公布。若您继续使用本平台，即视为接受变更后的条款。
      </p>
      <h3 class="fonWeight">八、账户终止</h3>
      <p>您可随时申请注销账户，平台方审核通过后将删除您的个人信息（法律法规另有规定的除外）。</p>
      <p>
        若您违反本协议或平台规则，平台方有权单方暂停、限制或终止您的账户使用，且无需退还已支付费用（如有），同时保留追究您法律责任的权利。
      </p>
      <h3 class="fonWeight">九、法律适用与争议解决</h3>
      <p>本协议适用中华人民共和国法律（港澳台地区除外）。</p>
      <p>
        因本协议产生的争议，双方应协商解决；协商不成，任何一方均有权向平台方所在地有管辖权的人民法院提起诉讼。
      </p>
      <h3 class="fonWeight">十、其他条款</h3>
      <p>本协议部分条款无效或被撤销，不影响其他条款的效力。</p>
      <p>平台方未行使或延迟行使权利，不视为放弃该权利，后续仍可主张。</p>
      <p>请仔细阅读本协议，确认接受后再注册使用本平台。如有疑问，可通过平台客服渠道联系我们。</p>
    </div>
    <div style="padding: 20px 0">
      <a-button :disabled="successBtn" type="primary" @click="readSuccess">我已阅读并知悉</a-button>
    </div>
  </a-modal>
  <div class="footer-text">
    <a>
      {{ brandStore.recordNumber }}
    </a>
  </div>
</template>

<style scoped lang="less">
.fonWeight {
  font-weight: 700;
}
.footer-text {
  position: fixed;
  bottom: 10px;
  left: 0;
  height: 50px;
  line-height: 50px;
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.user-register {
  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #1890ff;
  }
}

.main-app {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/pdr-bg.png');
  background-size: 100% 100%;
}

.main-logo {
  position: fixed;
  top: 10px;
  left: 10px;
  display: flex;
  height: 50px;
  width: 300px;
  // background: pink;

  .lp-logo {
    // width: 124px;
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .pdr-logo {
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .vertical-line {
    width: 2px; /* 竖线宽度 */
    height: 16px; /* 竖线高度，根据需要调整 */
    background-color: #999999; /* 竖线颜色，根据需要调整 */
    margin-top: 10px;
    margin-right: 28px;
  }
}

.main-div {
  display: flex;
  border-radius: 0.4rem;

  position: fixed;
  top: 26%;
  right: 14%;

  background: #ffffff;
  padding-top: 2rem;
  padding-bottom: 8rem;
  padding-left: 2rem;
  padding-right: 2rem;
  box-shadow: 0 10px 20px rgb(165 157 157 / 19%), 0 6px 6px rgb(255 255 255 / 23%);
}

@media (max-width: 700px) {
  /* 你可以根据需要调整这个断点 */
  .main-div {
    right: auto; /* 取消右对齐 */
    left: 50%; /* 将左边距设置为50% */
    transform: translateX(-50%); /* 向左移动自身宽度的50%，以实现居中 */
  }

  .title-desc {
    display: none;
  }
}

.tabs {
  display: flex;
  margin-bottom: 30px;
  font-weight: bolder;
  cursor: pointer;

  .left-box {
    flex: 1;
    text-align: right;
    padding-right: 1rem;
  }
  .right-box {
    flex: 1;
    padding-left: 1rem;
  }
}

.password-login {
  // 设置相对定位，以便伪元素可以相对于它定位
  position: relative;
  // 使得伪元素可以基于文本宽度来定位
  display: inline-block;
}

.password-login::after {
  // 伪元素的内容为空
  content: '';
  position: absolute;
  // 根据需要调整这个值以对齐到“码登”下方
  bottom: -2px;
  // 初始位置在元素宽度的中间
  left: 50%;
  // 短横线的宽高
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.register-account {
  position: relative;
  display: inline-block;
}

.register-account::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.title-desc {
  position: fixed;
  top: 36%;
  left: 16%;
  color: #163997;
  font-size: 36px;
  font-weight: bolder;
  min-width: 600px;
  width: 600px;
}
</style>
